import { getUserInfo } from '@/api/login'// 引入登录获取用户接口
import { getNowuserInfo, getMyPermissions } from '@/api/user'
import ElementUI from 'element-ui' // 引入饿了么
import router from '@/router/index'

// 导入移除token方法

import { removeToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: localStorage.getItem('house-token-8'), // 从本地读取token
    userInfo: {}, // 用户信息
    userPermissions: {} // 用户权限信息
  },
  mutations: {
    GETUSERINFO(state, data) {
      state.userInfo = data.user// 将用户个人信息保存至仓库
      state.token = data.jwt// 将token保存至仓库
    },
    UPDATEUSERINFO(state, res) {
      console.log(res)
      state.userInfo = res
    },
    // 设置登录用户的权限
    setUserPermissions(state, res) {
      state.userPermissions = res
    },
    // 删除token
    removeToken(state) {
      state.token = null
      state.userInfo = {}
      state.userPermissions = {}
      removeToken()
    }

  },
  actions: {
    async getUserInfo({ commit }, data) {
      const res = await getUserInfo(data)// 发送请求获取登录用户信息

      ElementUI.Message.success('登录成功')
      localStorage.setItem('house-token-8', res.jwt)// 存储本地token
      const result = await getMyPermissions()
      commit('setUserPermissions', result)
      router.push('/')
      commit('GETUSERINFO', res)
    },

    async updateUserinfo({ commit }) {
      console.log('465')

      const res = await getNowuserInfo()
      console.log(41, res)
      const result = await getMyPermissions()
      console.log(43, result)
      commit('setUserPermissions', result)// 保存用户权限

      commit('UPDATEUSERINFO', res)
    },
    // 移除token
    logout(store) {
      // 清除token
      store.commit('removeToken')
    }

  }
}

